{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# SMD (Server Machine Dataset)\n",
    "## 2. IsoForest"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "import numpy as np\n",
    "from sklearn.linear_model import SGDOneClassSVM\n",
    "from sklearn.svm import OneClassSVM\n",
    "from sklearn.preprocessing import StandardScaler, MinMaxScaler\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.ensemble import IsolationForest\n",
    "import os\n",
    "\n",
    "data_root = r\"E:\\迅雷下载\\异常检测\\SMD\"\n",
    "\n",
    "x_train = np.load(os.path.join(data_root, r\"SMD_train.npy\")) \n",
    "x_test = np.load(os.path.join(data_root, r\"SMD_test.npy\"))\n",
    "y_test = np.load(os.path.join(data_root, r\"SMD_test_label.npy\"))\n",
    "\n",
    "from sklearn.preprocessing import MinMaxScaler, StandardScaler\n",
    "scaler = StandardScaler()# StandardScaler() # MinMaxScaler()\n",
    "scaler.fit(x_train)\n",
    "x_train = scaler.transform(x_train)\n",
    "x_test = scaler.transform(x_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1e-05 err_train: 1.1292975063699437e-05\n",
      "0.0001 err_train: 0.00010022515369033251\n",
      "0.001 err_train: 0.0010008399150203625\n"
     ]
    }
   ],
   "source": [
    "from sklearn.ensemble import IsolationForest\n",
    "\n",
    "debug = True\n",
    "if debug:\n",
    "    for contamination in (1e-5, 1e-4, 1e-3,): # 2e-5, 3e-5, 1e-4, 1e-3, 1e-2, 0.1, 0.5, 2e-5, 3e-5,\n",
    "        clf = IsolationForest(n_estimators=100, max_samples='auto', contamination=contamination)\n",
    "\n",
    "        clf.fit(x_train)\n",
    "        preds_train = clf.predict(x_train)\n",
    "        err_train = sum(preds_train==-1)/len(preds_train)\n",
    "        print(contamination, \"err_train:\", err_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "err_train: 0.0010008399150203625\n"
     ]
    }
   ],
   "source": [
    "contamination = 1e-3\n",
    "clf = IsolationForest(n_estimators=200, max_samples='auto', contamination=contamination)\n",
    "\n",
    "clf.fit(x_train)\n",
    "preds_train = clf.predict(x_train)\n",
    "err_train = sum(preds_train==-1)/len(preds_train)\n",
    "print(\"err_train:\", err_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Classification report for classifier \n",
      "               precision    recall  f1-score   support\n",
      "\n",
      "         0.0     0.9608    0.9981    0.9791    678976\n",
      "         1.0     0.5826    0.0616    0.1114     29444\n",
      "\n",
      "    accuracy                         0.9592    708420\n",
      "   macro avg     0.7717    0.5298    0.5452    708420\n",
      "weighted avg     0.9451    0.9592    0.9430    708420\n",
      "\n",
      "\n",
      "Confusion matrix:\n",
      "[[677677   1299]\n",
      " [ 27631   1813]]\n"
     ]
    }
   ],
   "source": [
    "preds = clf.predict(x_test)\n",
    "preds[preds==1] = 0\n",
    "preds[preds==-1] = 1\n",
    "\n",
    "from sklearn import metrics\n",
    "print(\"Classification report for classifier \\n %s\\n\"\n",
    "      % ( metrics.classification_report(y_test, preds, digits=4)))\n",
    "print(\"Confusion matrix:\\n%s\" % metrics.confusion_matrix(y_test, preds))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.6702072438636475"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "scores = clf.score_samples(x_test)\n",
    "metrics.roc_auc_score(y_test, -scores)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py310",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
